package com.hugh.lagoucloudgateway9002.filter;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.hugh.lagoucloudgateway9002.config.SentinelHandlersClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Author: Hugh 统一认证
 * @Date: 2020/7/24
 */
@Slf4j
@Component  // 让容器扫描到，等同于注册了
public class UnifiedAuthenticationFilter implements GlobalFilter, Ordered {

    @Override
    @SentinelResource(value = "UnifiedAuthenticationFilter",blockHandlerClass = SentinelHandlersClass.class,
            blockHandler = "handleException",fallbackClass = SentinelHandlersClass.class,fallback = "handleError")
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String requestPath = request.getPath().toString();


        if(!requestPath.startsWith("/api/code")
        && !requestPath.startsWith("/api/user")
                && !requestPath.startsWith("/root")) {
            List<HttpCookie> lagouToken = request.getCookies().get("lagou_token");
            if(CollectionUtils.isEmpty(lagouToken)) {
                String data = "No Token! Request be denied!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
            String value = lagouToken.get(0).getValue();
//            LagouTokenEntity userByToken = lagouTokenService.findUserByToken(value);
//            if(StringUtils.isEmpty(userByToken.getEmail())){
//                String data = "validate Token! Request be denied!";
//                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
//                return response.writeWith(Mono.just(wrap));
//            }
            log.info("请求地址{}认证通过", requestPath);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
